package com.leetcode.leetcode1;

import java.util.HashMap;

/**
 * @program: 罗马数字转整数
 * @author: luhd
 * @create: 2021-08-24
 */
public class Practice13 {
    public static void main(String[] args) {
        String s = "MCMXCIV";
        int i = romanToInt(s);
        System.out.println(i);
    }
    public static int romanToInt(String s) {
        HashMap<Character, Integer> map = new HashMap<>();
        map.put('I',1);
        map.put('V',5);
        map.put('X',10);
        map.put('L',50);
        map.put('C',100);
        map.put('D',500);
        map.put('M',1000);
        int len = s.length();
        int fin = 0;
        for (int i = 0; i < len ; i++) {
            int current = map.get(s.charAt(i));
            if(i<len-1&& current<map.get(s.charAt(i+1))){   // 关键 IV  相当于5-1  需要了解罗马数字的组成规则
                fin -= current;
            }else {
                fin += current;
            }
        }
        return fin;
    }
}
